package com.ahjz.ahjzdemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ahjz.ahjzdemo.adapter.ListViewAdapter;
import com.ahjz.ahjzdemo.model.RemoteData;
import com.ahjz.ahjzdemo.tcp.TcpClient;
import com.github.mikephil.charting.data.BarEntry;

public class MainActivity extends Activity {
	private final String TAG = "MainActivity";

	private List<RemoteData> dataList;

	private TcpClient tcpClient;
	private ListView listView;
	private ListViewAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		dataList = new ArrayList<RemoteData>();

		loadView();
		loadDataFromRemote();
		loadTestData();
	}

	private void loadView() {
		listView = (ListView) findViewById(R.id.listview);
		adapter = new ListViewAdapter(this, dataList);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(MainActivity.this,
						DetailActivity.class);

				// 将从传感器获取的数据放入intent对象中，传递给DetailActivity
				// 测试数据
				float[] dataList = new float[10];
				for (int i = (int) 0; i < 10; i++) {
					float val = (float) (Math.random() * 50);
					dataList[i] = val;
				}

				intent.putExtra("datalist", dataList);
				MainActivity.this.startActivity(intent);
			}
		});

	}

	private void loadDataFromRemote() {
		tcpClient = new TcpClient();
		tcpClient.init("192.168.0.100", 5000);

		tcpClient.callback = new TcpClient.TcpClientCallback() {

			@Override
			public void onReceiveMessage(String msg) {
				Log.d(TAG, "onReceiveMessage: " + msg);
				// 解析传感器数据到dataList

			}
		};
		tcpClient.writeData("data");
	}

	private void loadTestData() {
		dataList.clear();
		for (int i = 0; i < 10; i++) {
			RemoteData data = new RemoteData();
			data.name = "CO2";
			float value = (float) (Math.random() * 50);
			data.number = value;

			// 根据数据大小显示不同颜色
			int color = Color.GREEN;
			if (value > 25) {
				color = Color.RED;
			} else if (value > 10) {
				color = Color.YELLOW;
			}
			data.color = color;

			dataList.add(data);
		}
		adapter.notifyDataSetChanged();
	}
}
